package com.myBlog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.myBlog.constants.SystemConstants;
import com.myBlog.domain.entity.LoginUser;
import com.myBlog.domain.entity.User;
import com.myBlog.mapper.MenuMapper;
import com.myBlog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名，查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        //判断是否查到用户，没有抛出异常
        Optional.ofNullable(user).orElseThrow(RuntimeException::new);

        //返回用户信息

        if (SystemConstants.ADMIN.equals(user.getType())){
            List<String> list = menuMapper.selectPermsByUserId(user.getId());

            return new LoginUser(user,list);
        }

        return new LoginUser(user,null);
    }
}
